﻿namespace Hippo.Agent.Lib.Runner
{
    using System;
    using System.Text.RegularExpressions;
    using Framework;
    using Framework.Model;
    using IronPython.Hosting;
    using Microsoft.Scripting.Hosting;

    public class ScriptHost
    {
        private const string TestNameExpression = @"class\s+(?<testName>.+)\s*\(\s*Hippo.Framework.TestBase";

        public TestBase GetTestClass(RunSpecification specification)
        {
            var engine = Python.CreateEngine();
            var scope = engine.CreateScope();

            var code = specification.Scenarios[0].ScriptCode;

            ScriptSource source = engine.CreateScriptSourceFromString(code);
            CompiledCode compiled = source.Compile();
            compiled.Execute(scope);

            var match = Regex.Match(code, TestNameExpression);
            if (!match.Success && !string.IsNullOrEmpty(match.Groups["testName"].Value))
            {
                throw new InvalidProgramException("Couldn't find a test case in supplied python code");
            }

            var testClass = match.Groups["testName"].Value;

            // Get the Python Class
            var testCase = (TestBase)engine.Operations.Invoke(scope.GetVariable(testClass));
            testCase.Run();

            return testCase;
        }
    }
}
